package com.ccx.myinterpreter;

import java.util.HashMap;
import java.util.Map;

public class Envirement {

    private Envirement parent;
    private Map<String, Object> data = new HashMap<>();

    public Envirement(Envirement parent) {
        this.parent = parent;
    }

    public Envirement getParent() {
        return parent;
    }

    public void setParent(Envirement parent) {
        this.parent = parent;
    }

    public Object get(String key) {
        Object val = data.get(key);
        if(val == null && parent != null) {
            return parent.get(key);
        }
        return val;
    }

    public Object getAt(String key, int instance) {
        return parentAt(instance).data.get(key);
    }

    public Envirement parentAt(int instance) {
        Envirement env = this;
        for (int i = 0; i < instance; i++) {
            env = env.parent;
        }
        return env;
    }

    public void declaration(String key, Object val) {
        if(data.containsKey(key)) 
            throw new RuntimeException("variable " + key + " already exist!");
        data.put(key, val);
    }

    public void set(String key, Object val) {
        Envirement env = exists(key);
        if(env != null)
            env.put(key, val);
        else
            throw new RuntimeException("variable " + key + " not exits!");
    }

    public void setAt(String key, Object val, Integer instance) {
        Envirement env = parentAt(instance);
        if(env != null)
            env.put(key, val);
        else
            throw new RuntimeException("variable " + key + " not exits!");
    }

    public Envirement exists(String key) {
        if(data.containsKey(key)) return this;
        return parent.exists(key);
    }

    public void put(String key, Object val) {
        data.put(key, val);
    }
    
}
